package net.yla.smartbus.core.util.mini;

import sun.rmi.runtime.Log;

/**
 * @Date: 2020-09-01 10:48
 * @Author: Being Nobody
 * @Version: 1.0
 */
public class BytesUtils {

    public static byte[] deleteAtIndex(byte[] bs, int index) {
        int length = bs.length - 1;
        byte[] ret = new byte[length];
        // 拷贝index前面的
        System.arraycopy(bs, 0, ret, 0, index);
        // 拷贝index后面的
        System.arraycopy(bs, index + 1, ret, index, length - index);
        return ret;
    }

    public static byte[] deleteWithValue(byte[] bs, int value) {
        // 获取下标
        int index = index(bs, value);
        // 移除
        if (index == -1) {
            return bs;
        }
        return deleteAtIndex(bs, index);
    }

    public static int index(byte[] bs, int value) {
        // 获取下标
        if (bs != null) {
            for (int i = 0; i < bs.length; i++) {
                byte b = bs[i];
                if (b == value) {
                    return i;
                }
            }
        }
        return -1;
    }

    public static int readU16bit(byte[] code, int index) {
        return (code[index] & 255) << 8 | code[index + 1] & 255;
    }

    public static int readS16bit(byte[] code, int index) {
        return code[index] << 8 | code[index + 1] & 255;
    }

    public static void write16bit(int value, byte[] code, int index) {
        code[index] = (byte) (value >>> 8);
        code[index + 1] = (byte) value;
    }

    public static int read32bit(byte[] code, int index) {
        return code[index] << 24 | (code[index + 1] & 255) << 16 | (code[index + 2] & 255) << 8 | code[index + 3] & 255;
    }

    public static void write32bit(int value, byte[] code, int index) {
        code[index] = (byte) (value >>> 24);
        code[index + 1] = (byte) (value >>> 16);
        code[index + 2] = (byte) (value >>> 8);
        code[index + 3] = (byte) value;
    }

    /**
     * @param parent the byte[] of parent
     * @param child  to add byte[] of child
     * @return
     */
    static byte[] copyChild(byte[] parent, byte[] child) {
        byte[] desc = new byte[parent.length + child.length];
        // copy parent
        System.arraycopy(parent, 0, desc, 0, parent.length);
        // copy child
        System.arraycopy(child, 0, desc, parent.length, child.length);

        return desc;
    }

    public static void main(String[] args) {
        byte[] child = {1, 2, 3, 4};
        byte[] parent = {1, 2, 3, 4, 5, 6, 7, 8,};
        byte[] desc = new byte[parent.length + 4];
        // copy parent
        System.arraycopy(parent, 0, desc, 0, parent.length);
        // copy child
        System.arraycopy(child, 0, desc, parent.length, child.length);

        System.out.println(desc);
    }

}
